
package Navigation;

import java.util.ArrayList;
import java.util.List;

import acs.ACS;

public class NavigationImpl implements INavigation {

    private ITopology topology;
    private int id;
    
    public NavigationImpl(){
        this.topology = new TopologyImpl();
        System.out.println("Start Reading Topology");
        topology.readTopology();
        System.out.println("Finished Reading Topology");
        id = -10000;
    }

    public ITopologyObject[] executeNavigation() {
    	System.out.println("Start Loading POIs");
    	ICrossingTopObj[] pointsOfInterest = readPointsOfInterest();
        System.out.println("Finished Loading POIs");
        System.out.println("Start Setting POIs");
        topology.setPointsOfInterest(pointsOfInterest);
        System.out.println("Finished Setting POIs");
        System.out.println("Start Calculating Best Tour");
        IAnt ants = new ACS(pointsOfInterest);
        pointsOfInterest = (ICrossingTopObj[]) ants.runTour();
        System.out.println("Finished Calculating Best Tour");
        System.out.println("Start Calculating Coordinates");
        List<ITopologyObject> tour = new ArrayList<ITopologyObject>();
        for(int i=0;i<pointsOfInterest.length;i++){
        	int start = i;
        	int finish = i+1;
        	if(i == pointsOfInterest.length-1){
        		finish = 0;
        	}
        	IAStar aStar = new AStar.AStarImpl(pointsOfInterest[start],pointsOfInterest[finish]);
        	ITopologyObject[] smallTour = (ITopologyObject[]) aStar.run();
        	for(int j=0;j<smallTour.length;j++){
        		tour.add(smallTour[j]);
        	}
        }
        System.out.println("Finished Calculating Coordinates");
        return (ITopologyObject[])tour.toArray(new ITopologyObject[]{});
    }

    private ICrossingTopObj[] readPointsOfInterest(){
    	String[] POIstrings = IO.getFileContent(LoadFromDatabase.FileNames.fileNamePOI);
    	ICrossingTopObj[] POIs = new CrossingTopologyObjectImpl[POIstrings.length];
    	for(int i=0;i<POIs.length;i++){
    		String[] coordinateString = POIstrings[i].split("\\s");
    		double x = Double.parseDouble(coordinateString[0]);
    		double y = Double.parseDouble(coordinateString[1]);
    		int id = getNewID();
    		POIs[i] = new CrossingTopologyObjectImpl(id + " " + x + " " + y);
    	}
    	return POIs;
    }
    
    private int getNewID(){
    	return id++;
    }
}
